const express = require("express");
const axios = require("axios");

const router = express.Router();

const cc = require("./cc");
const rds = require("./rds");
const logger = require("./logger");

router.get("/", (req, res) => {
    res.render("ai", {
        message: "务本去疾，共行同荣",
        icon: "weui-icon-success weui-icon_msg",
        description: "体验营养微生态医学无穷魅力",
    });
});

router.get("/chat", (req, res) => {
    res.redirect("https://ai.totemlife.cn/");
});

router.get("/gpt", (req, res) => {
    res.redirect("https://ai.totemlife.cn/");
});

router.get("/tutu", (req, res) => {
    res.redirect("https://work.weixin.qq.com/kfid/kfc3773a8afcf468ea2");
});

router.get("/tb", (req, res) => {
    res.redirect("https://work.weixin.qq.com/kfid/kfc22c04fd405b98c0f");
});

router.get("/huatuo", (req, res) => {
    res.redirect("https://www.huatuogpt.cn/");
});

// 渲染对话页面
router.get("/cc-chat", (req, res) => {
    const uid = req.session.totemUID; // 获取当前用户的 sessionId
    const style = req.query.style || "cc-chat";
    const hbs = style === "embed" ? "cc-embed" : "cc-chat";
    res.render(hbs, { uid });
});

// 处理用户的对话请求
router.post("/cc-chat", async (req, res) => {
    const { message, sessionId } = req.body;
    if (!message || !sessionId) {
        return res.status(400).json({ error: "缺少必要的参数" });
    }

    const url = `${cc.BASE_URL}/api/v1/workspace/${cc.DEFAULT_WORKSPACE_LINK}/chat`;
    const payload = {
        message,
        mode: "query",
        sessionId: `test-session-${sessionId}`,
        attachments: [],
    };
    const data = await cc.request("POST", url, payload);
    console.log("cc-chat data", data);

    // 处理 API 返回的结果
    res.json({
        reply: data
            ? data.textResponse
                ? data.textResponse
                : "抱歉，暂不能输出非文本回答"
            : "抱歉，我没有理解您的问题。",
    });
});

// 创建或获得CC系统用户id
router.get("/cc-sso", async (req, res) => {
    const totemUID = req.session.totemUID;
    let ccUID = req.session.ccUID;

    // 2.2 如果ccUID为零，创建CC系统用户
    if (ccUID === 0) {
        // 构造请求数据
        const username = `user${totemUID}`;
        const password = `U${totemUID}Pass0rd`;
        const requestData = {
            username: username,
            password: password,
            role: "default",
        };

        // 使用cc.request发起请求创建CC系统用户
        const createUserResponse = await cc.request(
            "POST",
            cc.BASE_URL + "/api/v1/admin/users/new",
            requestData
        );
        const user = createUserResponse.user;

        // 更新tutem_mall的用户表
        const updateUserSQL = `UPDATE tutem_mall.eb_user SET cc_user_id = ? WHERE uid = ?`;
        await rds.query(updateUserSQL, [user.id, totemUID]);

        // 更新ccUID及session中的ccUID
        ccUID = user.id;
        req.session.ccUID = user.id;
        req.session.save();

        // 获取当前所有可访问用户的cc_user_id
        const usersListSQL =
            "SELECT cc_user_id FROM tutem_mall.eb_user WHERE cc_user_id > 0";
        const [usersList] = await rds.query(usersListSQL);

        // 获取当前可访问用户列表
        const userIds = usersList.map((user) => user.cc_user_id);
        userIds.push(1, 2, 4); // 加入保留的三位cc_user_id

        // 使用cc.request更新Workspace用户列表
        const workspaceUpdateResponse = await cc.request(
            "POST",
            cc.BASE_URL +
                `/api/v1/admin/workspaces/${cc.DEFAULT_WORKSPACE_ID}/update-users`,
            {
                userIds: userIds,
            }
        );

        // 如果成功则走出ccUID为零的分支
        if (workspaceUpdateResponse.error) {
            res.status(500).send(
                "更新工作区失败：",
                workspaceUpdateResponse.error
            );
        }
    }

    // 2.3 ccUID大于零，请求SSO授权
    // 使用cc.request请求SSO授权
    const ssoAuthResponse = await cc.request(
        "GET",
        cc.BASE_URL + `/api/v1/users/${ccUID}/issue-auth-token`
    );
    logger.info(`CC SSO Authed: totemUID#${totemUID} ccUID#${ccUID}`);

    // 获取token和登录路径
    const loginPath = ssoAuthResponse.loginPath; //这里面已经包括了ssoAuthResponse.token

    // 构建重定向地址
    const redirectURL = `https://ai.totemlife.cn${loginPath}&redirectTo=/workspace/${cc.DEFAULT_WORKSPACE_LINK}`;

    // 重定向到CC系统的工作区
    res.redirect(redirectURL);
});

module.exports = router;
